package vip.websky.project.web.controller.user;

import com.alibaba.fastjson.JSON;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import vip.websky.project.common.error.CommonsRuntimeException;
import vip.websky.project.common.error.ErrorCode;
import vip.websky.project.common.error.ErrorMessage;
import vip.websky.project.common.utils.DateUtils;
import vip.websky.project.module.dto.RequestDTO;
import vip.websky.project.module.dto.ResponseDTO;
import vip.websky.project.module.dto.request.user.EditSysUserReqDTO;
import vip.websky.project.module.dto.request.user.GetSysUserReqDTO;
import vip.websky.project.user.error.UserErrorCode;
import vip.websky.project.user.error.UserErrorMessage;
import vip.websky.project.user.service.UserService;
import vip.websky.project.web.controller.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author YangYong E-mail:yang2048@qq.com
 * @Create 2017/8/28-18:11
 * <p>
 * 用户管理 控制层
 **/
@Slf4j
@Controller
@RequestMapping("/user/*")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = {"toList"}, method = RequestMethod.GET)
    public String toList() {
        return "/user/list";
    }

    @RequestMapping(value = {"toEdit"}, method = RequestMethod.GET)
    public String toEdit() {
        return "/user/edit";
    }

    @RequestMapping(method = RequestMethod.POST)
    public void edit(HttpServletRequest request, HttpServletResponse response, RequestDTO requestDTO,
                     EditSysUserReqDTO userReqDTO) {
        String param = JSON.toJSONString(userReqDTO);
        log.info("调用[UserController-edit]方法:参数: {}", param);
        requestDTO.setParam(param);
        ResponseDTO data;
        if (userReqDTO.getId() == null || userReqDTO.getId().equals("")) {
            data = userService.addUser(requestDTO);
        } else {
            data = userService.editUser(requestDTO);
        }
        sendMessages(request, response, data);
    }

    @RequestMapping(method = RequestMethod.GET)
    public void list(HttpServletRequest request, HttpServletResponse response, RequestDTO requestDTO,
                     GetSysUserReqDTO userReqDTO) {
        String param = JSON.toJSONString(userReqDTO);
        log.info("调用[UserController.list]方法:参数: {}", param);
        requestDTO.setParam(param);
        ResponseDTO data = userService.getUserList(requestDTO);
        sendMessages(request, response, data);
    }

    @RequestMapping(value = {"{id}"}, method = RequestMethod.GET)
    public ModelAndView getUser(RequestDTO requestDTO, ModelAndView view,
                                GetSysUserReqDTO userReqDTO) {
        String param = JSON.toJSONString(userReqDTO);
        log.info("调用[UserController.getUser]方法:参数: {}", param);
        requestDTO.setParam(param);
        ResponseDTO data = userService.getUser(requestDTO);
        view.addObject("user", data.getResult());
        view.setViewName("/user/edit");
        return view;
    }

    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public void removeUser(HttpServletRequest request, HttpServletResponse response, RequestDTO requestDTO,
                           GetSysUserReqDTO userReqDTO) {
        String param = JSON.toJSONString(userReqDTO);
        log.info("调用[UserController.removeUser]方法:参数: {}", param);
        requestDTO.setParam(param);
        ResponseDTO data = userService.removeUser(requestDTO);
        sendMessages(request, response, data);

    }

    /**
     * 登录login
     *
     * @param request
     * @param response
     * @param requestDTO
     * @param userReqDTO
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public void login(HttpServletRequest request, HttpServletResponse response, RequestDTO requestDTO,
                      GetSysUserReqDTO userReqDTO) {
        ResponseDTO data = new ResponseDTO<>();
        //参数校验
        boolean passed = true;
        if (StrUtil.isBlank(userReqDTO.getUserName())) {
            log.warn("用户编号为空");
            passed = false;
        }
        if (StrUtil.isBlank(userReqDTO.getPassword())) {
            log.warn("密码为空");
            passed = false;
        }
        if (!passed) {
            log.warn("参数校验不通过");
            throw new CommonsRuntimeException(ErrorCode.PARAMETER_ILLEGAL, ErrorMessage.PARAMETER_ILLEGAL);
        }
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userReqDTO.getUserName(), userReqDTO.getPassword());
        token.setRememberMe(StrUtil.isNotBlank(userReqDTO.getRemeber()) && userReqDTO.getRemeber() .equals("on"));
        try {
            user.login(token);
            data.setSuccess(true);
        } catch (UnknownAccountException e) {
            data.setStatusCode(UserErrorCode.USER_NOT_EXIST);
            data.setStatusMessage(UserErrorMessage.USER_NOT_EXIST);
        } catch (DisabledAccountException e) {
            data.setStatusCode(UserErrorCode.USER_STATUS_EXIST);
            data.setStatusMessage(UserErrorMessage.USER_STATUS_EXIST);
        } catch (IncorrectCredentialsException e) {
            data.setStatusCode(UserErrorCode.LOGIN_PASS_EXIST);
            data.setStatusMessage(UserErrorMessage.LOGIN_PASS_EXIST);
        } catch (CommonsRuntimeException e) {
            data.setStatusCode(e.getCode());
            data.setStatusMessage(e.getMessage());
            log.error("自定义异常:{},{}", e.getCode(), e.getMessage());
        } catch (Exception e){
            data.setStatusCode(ErrorCode.UNEXPECTED_ERROR);
            data.setStatusMessage(ErrorMessage.UNEXPECTED_ERROR);
            log.error("系统异常:{}", e);
        } finally {
            sendMessages(request, response, data);
        }
    }
}
